trigger CalculateAttainmentForClaims on Claim__c (after update) 
{
	Map<Id, Id> participantsMap = new Map<Id, Id>();
	Map<Id, Id> plansMap = new Map<Id, Id>();
	Claim__c[] updatedClaimsList = [select Attainment__c, Credit__c, Commission_Amount__c, Participant__c, Plan__c from Claim__c where id in :Trigger.new and Claim_Status__c = 'Approved'];
	for(Claim__c c : updatedClaimsList)
	{
		participantsMap.put(c.Participant__c, c.Participant__c);
		plansMap.put(c.Plan__c, c.Plan__c);
	}
	
	Plan__c[] plansList = [select Quota__c, OTE__c from Plan__c where id in :plansMap.keyset()];
	Double Quota = plansList[0].Quota__c;
	Double OTE = plansList[0].OTE__c;
	 
	List<Claim__c> creditClaimsList = [select Credit__c from Claim__c where Plan__c in :plansMap.keySet() and Participant__c in :participantsMap.keyset() and Claim_Status__c = 'Approved'];
	Double approvedClaimedAmount = 0;
	System.debug('Entered ');
	for(Claim__c c: creditClaimsList)
	{
		approvedClaimedAmount += c.Credit__c;
		System.debug('Approved Claim Amount '+approvedClaimedAmount);
	}
	System.debug('Approved Claim Amount '+approvedClaimedAmount+'   QUOTA '+Quota);
	
	if(approvedClaimedAmount >= Quota)
	{
		//Rate__c[] rateList = [select min__c, max]
		System.debug('IN IF Approved Claim Amount '+approvedClaimedAmount);
	}
	else
	{
		System.debug(' IN ELSE Approved Claim Amount '+approvedClaimedAmount);
		
		//Double ytdAttainment = 0;//recentAttainment + recentCommissionAmount;
/*		Plan_Participant__c[] ppList = [select YTD_Attainment__c from Plan_Participant__c where Plan__c in :plansMap.keyset() and Participant__c in :participantsMap.keySet()];
		for(Plan_Participant__c p :ppList)
			ytdAttainment += p.YTD_Attainment__c;
	*/
	
/*		Plan_Participant__c pp = new Plan_Participant__c(Participant__c = updatedClaimsList[0].Participant__c, Plan__c = updatedClaimsList[0].Plan__c, YTD_Attainment__c = updatedClaimsList[0].Commission_Amount__c);
		insert pp;
	*/		
	    try
	    {
			List<Plan_Participant__c> ppList = new List<Plan_Participant__c>();
			for(Claim__c c: updatedClaimsList)
		    {
				Plan_Participant__c pp = new Plan_Participant__c(Participant__c = c.Participant__c, Plan__c = c.Plan__c, YTD_Attainment__c = c.Commission_Amount__c);
				ppList.add(pp);
				System.debug('Plan Participants size is '+ppList.size());
		    }
		    if(ppList.size() > 0)
				insert ppList;
				
			System.debug('Plan Participants size is '+ppList.size());
	    }
	    catch(Exception e)
	    {
	    	System.debug(e.getMessage());	
	    }
	}
}